package com.macro.mall.portal.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.macro.mall.common.api.CommonResult;
import com.macro.mall.model.CmsSubject;
import com.macro.mall.model.PmsProduct;
import com.macro.mall.model.PmsProductCategory;
import com.macro.mall.portal.domain.HomeContentResult;
import com.macro.mall.portal.service.HomeService;
import com.macro.mall.portal.service.OmsPortalOrderService;
import com.macro.mall.portal.util.OrderUtil;
import com.macro.mall.portal.vo.JscodeVo;
import com.macro.mall.portal.vo.LitePayVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@Controller
@Api(tags = "PayController")
@Tag(name = "PayController", description = "支付")
@RequestMapping("/pay")
public class PayController {

    @Value("${pay.url}")
    private String payUrl;

    @Autowired
    private OmsPortalOrderService portalOrderService;


    /**
     * 获取openid
     **/
    @ApiOperation("获取openid")
    @PostMapping("/payJscode")
    @ResponseBody
    public CommonResult payJscode(@RequestParam(value = "jscode") String jscode) {

        if (ObjectUtils.isEmpty(jscode)) {
            return CommonResult.failed("code不能为空");
        }

        String responce = HttpUtil.get("https://api.weixin.qq.com/sns/jscode2session" +
                "?appid=wxc7e0f0c39213e0af" +
                "&secret=5065db8635b81c81f50cd22d824f96bc" +
                "&js_code=" + jscode +
                "&grant_type=authorization_code");

        JSONObject jsonObject = JSONUtil.parseObj(responce);
        String openid = jsonObject.getStr("openid");
        if (ObjectUtils.isEmpty(openid)) {
            return CommonResult.failed("invalid code");
        }

        JscodeVo vo = new JscodeVo();
        vo.setOpenid(openid);
        vo.setMchOrderNo(OrderUtil.getOrderNo());

        return CommonResult.success(vo);
    }

    /**
     * payInfo
     **/
    @ApiOperation("payInfo")
    @PostMapping("/payInfo")
    @ResponseBody
    public CommonResult payInfo(
            @RequestParam(value = "orderId") String orderId,
            @RequestParam(value = "payType") String payType,
            @RequestParam(value = "mchOrderNo") String mchOrderNo,
            @RequestParam(value = "amount") Long amount,
            @RequestParam(value = "wayCode") String wayCode,
            @RequestParam(value = "orderTitle") String orderTitle,
            @RequestParam(value = "channelExtra") String channelExtra
    ) {


        JSONObject estr = new JSONObject();
        estr.set("source", "1");
        estr.set("mallOrderId", orderId);
        estr.set("payType", payType);

        String extParam = estr.toString();
        String url = payUrl + "/api/pay/payLite?mchOrderNo=" + mchOrderNo +
                "&amount=" + amount +
                "&wayCode=" + wayCode +
                "&orderTitle=" + orderTitle +
                "&channelExtra=" + channelExtra +
                "&extParam=" + extParam;

        String result = HttpRequest.post(url)
                .header("Authorization", "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoiNiIsImtleSI6Im1hbGwifQ.E6LGGDZuwJWWlu2sevcg1ixWPaRde04fuh0N5OQqrJs")//头信息，多个头信息多次调用此方法即可
//                .form(paramMap)//表单内容
//                .timeout(20000)//超时，毫秒
                .execute().body();

        JSONObject jsonObject = JSONUtil.parseObj(result);
        String code = jsonObject.getStr("code");
        if (!"0".equals(code)) {
            return CommonResult.failed(jsonObject.getStr("msg"));
        }

        JSONObject j1 = JSONUtil.parseObj(jsonObject.getStr("data"));
        JSONObject j2 = JSONUtil.parseObj(j1.getStr("payData"));

        LitePayVo vo = JSONUtil.toBean(j1.getStr("payData"), LitePayVo.class);
        vo.setPackageStr(j2.getStr("package"));

        return CommonResult.success(vo);
    }

    /**
     * payInfo
     **/
    @ApiOperation("payFinish")
    @PostMapping("/payFinish")
    @ResponseBody
    public CommonResult payFinish(
            @RequestParam(value = "orderId") Long orderId,
            @RequestParam(value = "payType") Integer payType
    ) {

        Integer count = portalOrderService.paySuccess(orderId,payType);

        log.info("支付成功：{}，{}，{}", orderId, payType, count);

        return CommonResult.success("ok");
    }

}
